﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.Security;

namespace GMS.BIZ
{
    public class Account
    {
        /*property:
         *  string loginID;  (get)
         *  char roleCurrent;  (get)
         *  arraylist roleList; (get)所有该用户存在的角色 
         *  decimal counts; (get)
         */
        private string loginID;
        public string LoginID
        {
            get { return loginID; }
            //set { loginID = value; }
        }
        private char roleCurrent;
        public char RoleCurrent
        {
            get { return roleCurrent; }
            //set { roleCurrent = value; }
        }
        private ArrayList roleList;
        public ArrayList RoleList
        {
            get { return roleList; }
            //set { roleList = value; }
        }
        private decimal counts;

        public decimal Counts
        {
            get { return counts; }
            //set { counts = value; }
        }

        public Account()
        {
            ArrayList newArrayList = new ArrayList();
            this.roleList = null;
            this.roleList = newArrayList;
        }

        /// <summary>
        /// 更改当前角色
        /// </summary>
        /// <param name="newRole">新角色</param>
        public string ChangeCurrentRole(char newRole)
        {
            //newRole是否属于roleList中
            //失败
            //return ErrorMessage.NoSuchData;
            bool ok = this.roleList.Contains(newRole.ToString());
            if (!ok) return ErrorMessage.NoSuchData;

            //删除旧Role的Session
            //创建新的Session
            string teacherID = string.Empty;
            switch (this.roleCurrent)
            {
                case 'a': teacherID = ((Admin)HttpContext.Current.Session["Admin"]).TeacherId;
                    HttpContext.Current.Session.Remove("Admin"); break;
                case 'c': teacherID = ((ClassTeacher)HttpContext.Current.Session["ClassTeacher"]).TeacherId;
                    HttpContext.Current.Session.Remove("ClassTeacher"); break;
                case 't': teacherID = ((Teacher)HttpContext.Current.Session["Teacher"]).TeacherId;
                    HttpContext.Current.Session.Remove("Teacher"); break;
                default: break;
            }
            switch (newRole)
            {
                case 'a': Admin newAdmin = new Admin(teacherID);
                    HttpContext.Current.Session.Add("Admin", newAdmin); break;
                case 'c': ClassTeacher newClassTeacher = new ClassTeacher(teacherID);
                    HttpContext.Current.Session.Add("ClassTeacher", newClassTeacher); break;
                case 't': Teacher newTeacher = new Teacher(teacherID);
                    HttpContext.Current.Session.Add("Teacher", newTeacher); break;
                default: break;
            }
            
            //成功：更改roleCurrent
            this.roleCurrent = newRole;
            return ErrorMessage.OK;            
        }
        
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        public string ChangePassword(string oldPassword, string newPassword)
        {
            //转MD5
            string mOld = FormsAuthentication.HashPasswordForStoringInConfigFile(oldPassword, "MD5").ToLower();
            GMS.ORM.DAL.SLogin optLogin = new GMS.ORM.DAL.SLogin();
            GMS.ORM.Model.SLogin myLogin = new GMS.ORM.Model.SLogin();
            myLogin = optLogin.GetModel(this.loginID);                       
            //校对旧的密码
            //更改新的密码
            if (mOld != myLogin.password) return ErrorMessage.DataNotMatch;
            else
            {
                myLogin.password = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword, "MD5").ToLower();
                bool ok = optLogin.Update(myLogin);
                if (!ok) return ErrorMessage.DBOptError;
                else return ErrorMessage.OK;
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginID">登录ID</param>
        /// <param name="password">密码</param>
        static public string Login(string loginID, string password)
        {
            //转MD5
            string mPass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5").ToLower();
            //测试用户名密码是否匹配
            GMS.ORM.DAL.SLogin optLogin = new GMS.ORM.DAL.SLogin();
            GMS.ORM.Model.SLogin myLogin = new GMS.ORM.Model.SLogin();
            myLogin = optLogin.GetModel(loginID);
            //string oPass = FormsAuthentication.HashPasswordForStoringInConfigFile(myLogin.password, "md5").ToLower();           
            //失败返回false
            if (myLogin==null || mPass != myLogin.password) return ErrorMessage.DataNotMatch;

            //成功
            //（1）创建Account对象，currentRole赋初值优先级为“s”（student），“t”（teacher），“c”（classteacher），“a”（admin）
            //（2）将Account对象写入session["Account"]中
            //（3）拿出idmap，根据currentRole创建student对象、teacher对象、classteacher对象或admin对象并写入session["..."]中。（...为具体对象名）
            //（4）登录次数counts+1
            //返回true
            Account myAccount = new Account();
            myAccount.loginID = loginID;              
            string roleInDB = myLogin.role.ToString().Trim();
            if (roleInDB.Contains("s")) myAccount.roleList.Add("s");
            if (roleInDB.Contains("t")) myAccount.roleList.Add("t");
            if (roleInDB.Contains("c")) myAccount.roleList.Add("c");
            if (roleInDB.Contains("a")) myAccount.roleList.Add("a");

            myAccount.counts = (myLogin.counts == null) ? 1 : decimal.Parse(myLogin.counts.ToString()) + 1;
            if (myLogin.role.Contains('s')) myAccount.roleCurrent = 's';
            else if (myLogin.role.Contains('t')) myAccount.roleCurrent = 't';
            else if (myLogin.role.Contains('c')) myAccount.roleCurrent = 'c';
            else myAccount.roleCurrent = 'a';

            HttpContext.Current.Session["Account"] = myAccount;

            if (myAccount.roleCurrent == 's')
            {
                Student myStudent = new Student(myLogin.idmap);
                HttpContext.Current.Session["Student"]= myStudent;
            }
            else if (myAccount.roleCurrent == 't')
            {
                Teacher myTeacher = new Teacher(myLogin.idmap);
                HttpContext.Current.Session["Teacher"] = myTeacher;
            }
            else if (myAccount.roleCurrent == 'c')
            {
                ClassTeacher myClassTeacher = new ClassTeacher(myLogin.idmap);
                HttpContext.Current.Session["ClassTeacher"] = myClassTeacher;
            }
            else
            {
                Admin myAdmin = new Admin(myLogin.idmap);
                HttpContext.Current.Session["Admin"] = myAdmin ;
                HttpContext.Current.Session["IsAuthorizedupload"] = true;
            }

            myLogin.counts++;
            bool ok = optLogin.Update(myLogin);
            if (ok == true) return ErrorMessage.OK;
            else return ErrorMessage.DBOptError;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="name">登录名</param>
        /// <param name="password">密码</param>
        /// <param name="idmap">用户id映射</param>
        /// <param name="ifAdmin">是否管理员</param>
        /// <param name="ifClassTeacher">是否班主任</param>
        /// <param name="ifTeacher">是否教师</param>
        /// <param name="ifStudent">是否学生</param>
        static public string Add(string name, string password, string idmap, bool ifAdmin, bool ifClassTeacher, bool ifTeacher, bool ifStudent)
        {
            //检查name是否存在
            GMS.ORM.DAL.SLogin optLogin = new GMS.ORM.DAL.SLogin();
            if (optLogin.Exists(name) == true) return ErrorMessage.AlreadyExitsData;
            //检查idmap绑定的人是否存在
            if (ifTeacher == true || ifClassTeacher == true)
            {
                if (Staff.GetName(name) == ErrorMessage.NoSuchData) return ErrorMessage.NoSuchData;
            }
            if (ifStudent == true)
            {
                if (Student.GetName(name) == ErrorMessage.NoSuchData) return ErrorMessage.NoSuchData;
            }
            //if (optLogin.Exists(idmap) == false) return ErrorMessage.NoSuchData;
            //转MD5
            string mPass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5").ToLower();
            //成功添加
            GMS.ORM.Model.SLogin myLogin = new GMS.ORM.Model.SLogin();
            myLogin.name = name;
            myLogin.password = mPass;
            myLogin.counts = 0;
            myLogin.idmap = idmap;
            myLogin.role = string.Empty;
            if (ifAdmin) myLogin.role = myLogin.role + "a";
            if (ifClassTeacher) myLogin.role = myLogin.role + "c";
            if (ifTeacher) myLogin.role = myLogin.role + "t";
            if (ifStudent) myLogin.role = myLogin.role + "s";
            bool ok = optLogin.Add(myLogin);
            if (!ok) return ErrorMessage.DBOptError;
            else return ErrorMessage.OK;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="name">登录用户名</param>      
        static public string Delete(string name)
        {
            //检查是否存在
            GMS.ORM.DAL.SLogin optLogin = new GMS.ORM.DAL.SLogin();
            if (!optLogin.Exists(name)) return ErrorMessage.NoSuchData;
            //成功删除
            bool ok = optLogin.Delete(name);
            if (!ok) return ErrorMessage.DBOptError;
            else return ErrorMessage.OK;
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="name">登录名</param>
        /// <param name="password">密码(若为空不更改密码)</param>
        /// <param name="idmap">id映射</param>
        /// <param name="ifAdmin">是否管理员</param>
        /// <param name="ifClassTeacher">是否班主任</param>
        /// <param name="ifTeacher">是否教师</param>
        /// <param name="ifStudent">是否学生</param>
        /// <returns></returns>
        static public string Update(string name, string password, string idmap, bool ifAdmin, bool ifClassTeacher, bool ifTeacher, bool ifStudent)
        {
            //检查name是否不存在
            GMS.ORM.DAL.SLogin optSLogin = new GMS.ORM.DAL.SLogin();
            GMS.ORM.Model.SLogin mySlogin = new GMS.ORM.Model.SLogin();
            if (!optSLogin.Exists(name)) return ErrorMessage.NoSuchData;

            //检查idmap绑定的人是否不存在
            if (optSLogin.Exists(name) == false) return ErrorMessage.NoSuchData;

            //转MD5
            string mPass;
            if (password == string.Empty) mPass = optSLogin.GetModel(name).password;
            else mPass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5").ToLower();
            //成功修改
            mySlogin.name = name;
            mySlogin.password = mPass;
            mySlogin.counts = 0;
            mySlogin.idmap = idmap;
            mySlogin.role = string.Empty;
            if (ifAdmin) mySlogin.role = mySlogin.role + "a";
            if (ifClassTeacher) mySlogin.role = mySlogin.role + "c";
            if (ifTeacher) mySlogin.role = mySlogin.role + "t";
            if (ifStudent) mySlogin.role = mySlogin.role + "s";
            bool ok = optSLogin.Update(mySlogin);
            if (!ok) return ErrorMessage.DBOptError;
            else return ErrorMessage.OK;
        }
        
        /// <summary>
        /// 获取特定用户列表
        /// </summary>
        /// <param name="ifAdmin">是否管理员</param>
        /// <param name="ifClassTeacher">是否班主任</param>
        /// <param name="ifTeacher">是否教师</param>
        /// <param name="ifStudent">是否学生</param>
        /// <param name="nameLike">名字包含</param>
        /// <returns></returns>
        static DataSet GetList(bool ifAdmin, bool ifClassTeacher, bool ifTeacher, bool ifStudent, string nameLike)
        {
            //name采用like搜索
            if (ifStudent == true)
            {
                GMS.ORM.DAL.GStudent optStudent = new GMS.ORM.DAL.GStudent();
                return optStudent.GetList("std_name like '%" + nameLike + "%'");
            }
            else if (ifAdmin==true || ifClassTeacher==true || ifTeacher==true)
            {
                GMS.ORM.DAL.UTeacher optTeacher = new GMS.ORM.DAL.UTeacher();
                return optTeacher.GetList("tch_name like '%" + nameLike + "%'");
            }
            else return null;
        }

        /// <summary>
        /// 获取idmap对应的用户名
        /// </summary>
        /// <param name="idmap">id映射</param>
        /// <returns>登录用户名</returns>
        static public string GetLoginName(string idmap)
        {
            GMS.ORM.DAL.SLogin optSlogin = new GMS.ORM.DAL.SLogin();
            DataSet myDs = optSlogin.GetList("idmap='" + idmap + "'");
            if (myDs == null) return string.Empty;
            return myDs.Tables[0].Rows[0]["name"].ToString();
        }

        static public string GetRoles(string idmap)
        {
            GMS.ORM.DAL.SLogin optSlogin = new GMS.ORM.DAL.SLogin();
            DataSet myDs = optSlogin.GetList("idmap='" + idmap + "'");
            if (myDs == null) return string.Empty;
            return myDs.Tables[0].Rows[0]["role"].ToString();
        }
    }
}
